package com.yimo.controller;

import com.xiaoju.automarket.knife.util.StringUtil;
import com.yimo.chromedriver.*;
import com.yimo.common.exception.BaseErrors;
import com.yimo.common.exception.BusinessException;
import com.yimo.common.response.BaseResponse;
import com.yimo.common.util.ExcelUtil;
import com.yimo.util.DownloadUtil;
import com.yimo.util.FileDescUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * create by jsm on 2018/9/29
 */
@RestController
@RequestMapping("/crawler")
public class CrawerController {

    @Value("${chromedriver.savePath:/Users/yimouser/Documents/weibo/xhs}")
    private String savePath;
    private volatile static boolean xhsStart = false;
    @Resource
    private Alibaba alibaba;
    @Resource
    private XiaoHongShu xiaoHongShu;
    @Resource
    private HunLiJi hunLiJi;
    @Resource
    private Nineteen nineteen;
    @Resource
    private Weibo weibo;

    @GetMapping("xhs")
    public BaseResponse <Void> xhs(String url) {
        try {
            if (xhsStart == true) {
                throw new BusinessException(BaseErrors.SERVER_ERROR.setEmArgs("小红书上一轮爬虫还在进行中，请稍后再试").setArgs("小红书上一轮爬虫还在进行中，请稍后再试"));
            }
            xhsStart = true;
            xiaoHongShu.climb(url, savePath + "/xhs");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(BaseErrors.SERVER_ERROR.setEmArgs("服务器开小差").setArgs("服务器开小差"));
        } finally {
            xhsStart = false;
        }
        return new BaseResponse <>();
    }

    @GetMapping("listfiles")
    public BaseResponse <List <FileDesc>> listfiles(@RequestParam(required = false) String absolutePath) {
        if (StringUtil.isEmpty(absolutePath)) {
            absolutePath = savePath;
        }
        return new BaseResponse <>(FileDescUtil.getFileDesc(absolutePath));
    }


    @GetMapping("download")
    public void fileList(String absolutePath, HttpServletResponse httpServletResponse) {
        File file = new File(absolutePath);
        if (file.isDirectory()) {
            throw new BusinessException(BaseErrors.SERVER_ERROR.setArgs("不能下载文件夹").setEmArgs("不能下载文件夹"));
        }
        DownloadUtil.downloadFile(absolutePath, file.getName(), httpServletResponse);
    }

    @PostMapping("upload1688ShopAllProduct")
    public BaseResponse upload1688ShopAllProduct(@RequestBody Map <String, String> param) throws InterruptedException {
        alibaba.setUrl(param.get("url"));
        if (param.get("categoryId") != null) {
            alibaba.setCagtegoryId(Long.parseLong(param.get("categoryId")));
        }
        alibaba.setShopId(Long.parseLong(param.get("shopId")));
        alibaba.setPlatformId(Long.parseLong(param.get("platformId")));
        alibaba.climb();
        return new BaseResponse();
    }

    @PostMapping("uploadSingle1688Product1688")
    public BaseResponse uploaduploadSingle1688Product16881688(MultipartFile file, Long categoryId, Long shopId, Long platformId) throws Exception {
        alibaba.setPlatformId(platformId);
        alibaba.setShopId(shopId);
        alibaba.setCagtegoryId(categoryId);
        ChromeDriver chromeDriver = null;
        Workbook workbook = ExcelUtil.getWorkbook(file.getInputStream(), file.getOriginalFilename());
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);
            for (int j = 1; j < sheet.getLastRowNum()+1; j++) {
                Row row = sheet.getRow(j);
                short lastCellNum = row.getLastCellNum();
                if (lastCellNum < 2) {
                    continue;
                } else {
                    Cell cell = row.getCell(1);
                    alibaba.setUrl(cell.getStringCellValue());
                }
                try {
                    chromeDriver = alibaba.climbSingle();
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }

            }
        }

        return new BaseResponse();
    }

    @GetMapping("uploadSingle")
    public BaseResponse uploadSingle(Long productId, Long categoryId, Long shopId, Long platformId) {
        alibaba.setPlatformId(platformId);
        alibaba.setShopId(shopId);
        alibaba.setCagtegoryId(categoryId);
        alibaba.setUrl("https://detail.1688.com/offer/" + productId + ".html?spm=b26110380.sw1688.mof001.191.3a252a56WU28wb");
        ChromeDriver chromeDriver = alibaba.climbSingle();
        chromeDriver.quit();
        chromeDriver = null;

        return new BaseResponse();
    }

    @PostMapping("hlj")
    public BaseResponse hlj(String url) throws IOException {
        hunLiJi.setUrl(url);
        hunLiJi.climb();
        return new BaseResponse();
    }

    @PostMapping("hljExcel")
    public BaseResponse hljexcel(MultipartFile file) throws IOException {
        ChromeDriver chromeDriver = null;
        Workbook workbook = ExcelUtil.getWorkbook(file.getInputStream(), file.getOriginalFilename());
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);
            for (int j = 1; j < sheet.getLastRowNum(); j++) {
                Row row = sheet.getRow(j);
                short lastCellNum = row.getLastCellNum();
                if (lastCellNum < 4) {
                    continue;
                } else {
                    Cell cell = row.getCell(3);
                    hunLiJi.setUrl(cell.getStringCellValue());
                }
                try {
                    chromeDriver = hunLiJi.climb();

                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }

            }
        }
        if (chromeDriver != null) {
            chromeDriver.quit();
        }
        return new BaseResponse();
    }

    @PostMapping("nineteen")
    public BaseResponse nineteen(String url) throws IOException {
        nineteen.setUrl(url);
        nineteen.climb();
        return new BaseResponse();
    }

    @PostMapping("nineteenExcel")
    public BaseResponse nineteenExcel(MultipartFile file) throws IOException {

        return new BaseResponse();
    }

    @GetMapping("weibo")
    public BaseResponse weibo(String[] keywords) throws Exception {
        ChromeDriver chromeDriver = null;
        for (String keyword : keywords) {
            chromeDriver = weibo.climb("15168300762", "sha5362sxx", keyword);
        }
        if (chromeDriver != null) {
            chromeDriver.quit();
            chromeDriver = null;
        }

        return new BaseResponse();
    }
}
